<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Object relational mapping with iBATIS</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="jee tutorial, java, web application, Object relational mapping with iBATIS">
<meta name="description" content="This part of the Java EE 5 tutorial covers Object relational mapping with iBATIS.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Contents">Contents</a>


<h1>Object relational mapping with iBATIS</h1>

<p>
In this part of the JEE programming tutorial, we will talk about the 
object relational mapping with iBATIS.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 

<p>
<b>Object Relational Mapping</b>, <b>ORM</b> is a programming technique for 
converting data between relational databases and object oriented programming 
languages. Data is handled differently in both systems. The problem that arises from these
differences is called the <b>object-relational impedance mismatch</b>.
The ORM tools were created to help application programmers to cope with these 
issues. Hibernate or Toplink are two of such tools. In large JEE applications 
developers mostly do not work directly with SQL, but they use ORM tools. 
</p>

<p>
<b>iBATIS</b> is another ORM mapping tool. I chose iBATIS for these 
tutorials, because it is simple and easy to use. 
iBATIS can be used with Java, .NET or Ruby. It is developed by the 
Apache Software Foundation. Simplicity is the biggest advantage over other ORM tools.  
</p>



<h2>Commmand line example</h2>


<p>
The first example will be command line. The example will get all data from a 
database table using iBATIS. We will use books database and books table again. 
</p>

<pre class="code">

mysql> describe books;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment | 
| author | varchar(30)  | YES  |     | NULL    |                | 
| title  | varchar(40)  | YES  |     | NULL    |                | 
| year   | int(11)      | YES  |     | NULL    |                | 
| remark | varchar(100) | YES  |     | NULL    |                | 
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.23 sec)
</pre>

<p>
This is the books table. 
</p>


<div class="codehead">sqlMapConfig.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;

&lt;!DOCTYPE sqlMapConfig 
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"&gt;

&lt;sqlMapConfig&gt;

 &lt;transactionManager type="JDBC" commitRequired="false"&gt;
  &lt;dataSource type="SIMPLE"&gt;
   &lt;property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/&gt;
   &lt;property name="JDBC.ConnectionURL" 
       value="jdbc:mysql://localhost:3306/books"/&gt;
   &lt;property name="JDBC.Username" value="root"/&gt;
   &lt;property name="JDBC.Password" value=""/&gt;
   &lt;/dataSource&gt;
 &lt;/transactionManager&gt;

 &lt;sqlMap resource="ibatis/Books.xml"/&gt;

&lt;/sqlMapConfig&gt;
</pre>

<p>
This is the configuration file for the iBATIS. We can give it an arbitrary name. 
Inside the configuration file, we define the datasource an various sql map files. 
We use the MySQL database. 
</p>

<div class="codehead">Book.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;

&lt;!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd"&gt;

&lt;sqlMap namespace="Book"&gt;
    
&lt;typeAlias alias="Book" type="ibatis.Book"/&gt;

  &lt;select id="selectAllBooks" resultClass="ibatis.Book"&gt;
    select * from books
  &lt;/select&gt;

&lt;/sqlMap&gt;
</pre>

<p>
This is the sql map file. This file will map a java class to a database 
table. In our case the Java class is Book.java
and the table is books in the books database. 
</p>

<div class="codehead">Book.java</div>
<pre class="code">
package ibatis;

public class Book {

    private int id;
    private String author;
    private String title;
    private String year;
    private String remark;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getBookId() {
        return id;
    }

    public void setBookId(int id) {
        this.id = id;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }
}
</pre>

<p>
This is the Books bean java class with all its properties and setter 
and getter methods. 
</p>

<div class="codehead">Main.java</div>
<pre class="code">
package ibatis;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

public class Main {

  public static void main(String[] args)
          throws IOException, SQLException {

    Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
    SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

    List&lt;Book&gt; books = (List&lt;Book&gt;) 
        sqlMap.queryForList("selectAllBooks");

    for (Book a : books) {
        System.out.println(a.getAuthor() + " : " + a.getTitle());
    }
  }
}
</pre>

<p>
This code loads the configuration file, receives the data using the 
<code>queryForList()</code> method call and 
prints authors and titles of books to the console. 
</p>

<pre class="code">
$ java -jar ibatis.jar 
Leo Tolstoy : War and Peace
Leo Tolstoy : Anna Karenina
ralf reuth : rommel
Balzac : Goriot
David Schwartz : The magic of thinking big
Johannes Leeb : Der Nuernberger prozess
Siegfried Knappe : German Soldier
Kertész Imre : Sorstalanság
Napoleon Hill : Think and grow rich
Brett Spell : Professional Java Programming
</pre>

<p>
This is the result that we get. 
</p>


<h2>Web example</h2>

<p>
The next example will enhance the previous one. In addition to selecting 
all books, we will also have the ability
to insert and delete books. 
</p>


<div class="codehead">style.css</div>
<pre class="code">
* { font-size: 12px; font-family: Verdana }

input { border: 1px solid #ccc }

a#currentTab {
    border-bottom:1px solid #fff;
}

a { color: black; text-decoration:none;
    padding:5px; border: 1px solid #aaa;
}

a:hover { background: #ccc; cursor: pointer; }

td { border: 1px solid #ccc; padding: 3px }
th { border: 1px solid #ccc; padding: 3px; 
    background: #009999; color: white }

.navigator { border-bottom:1px solid #aaa; width:300px; padding:5px }

.hovered { background-color: #c4dcff }
.selected { background-color: #a5ffb8 }
.highlighted { background-color: #e33146 }
.unselected { background-color: #ffffff }
</pre>

<p>
Simple css file used in our example. 
</p>

<div class="codehead">web.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app version="2.5"&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;GetAllBooks&lt;/servlet-name&gt;
        &lt;servlet-class&gt;com.zetcode.GetAllBooks&lt;/servlet-class&gt;
    &lt;/servlet&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;InsertBook&lt;/servlet-name&gt;
        &lt;servlet-class&gt;com.zetcode.InsertBook&lt;/servlet-class&gt;
    &lt;/servlet&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;DeleteBooks&lt;/servlet-name&gt;
        &lt;servlet-class&gt;com.zetcode.DeleteBooks&lt;/servlet-class&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;GetAllBooks&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/GetAllBooks&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;InsertBook&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/InsertBook&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;DeleteBooks&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/DeleteBooks&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
    &lt;session-config&gt;
        &lt;session-timeout&gt;
            30
        &lt;/session-timeout&gt;
    &lt;/session-config&gt;
    &lt;welcome-file-list&gt;
        &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
        &lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>

<p>
This is the <code>web.xml</code> file. Here we configure our 
three servlets. 
</p>

<div class="codehead">sqlMapConfig.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;

&lt;!DOCTYPE sqlMapConfig 
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"&gt;

&lt;sqlMapConfig&gt;

 &lt;transactionManager type="JDBC" commitRequired="false"&gt;
  &lt;dataSource type="SIMPLE"&gt;
   &lt;property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/&gt;
   &lt;property name="JDBC.ConnectionURL" 
       value="jdbc:mysql://localhost:3306/books"/&gt;
   &lt;property name="JDBC.Username" value="root"/&gt;
   &lt;property name="JDBC.Password" value=""/&gt;
   &lt;/dataSource&gt;
 &lt;/transactionManager&gt;

 &lt;sqlMap resource="ibatis/Books.xml"/&gt;

&lt;/sqlMapConfig&gt;
</pre>

<p>
The <code>sqlMapConfig.xml</code> file is unchanged. 
</p>

<div class="codehead">Book.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;

&lt;!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd"&gt;

&lt;sqlMap namespace="Book"&gt;
    
&lt;typeAlias alias="Book" type="com.zetcode.Book"/&gt;

  &lt;select id="selectAllBooks" resultClass="com.zetcode.Book"&gt;
    select * from books
  &lt;/select&gt;

  &lt;insert id="insertBook" parameterClass="com.zetcode.Book"&gt;
    insert into books (
      author,
      title,
      year,
      remark )
    values (
      #author#, #title#, #year#, #remark#
    )
  &lt;/insert&gt;

  &lt;delete id="deleteBooks" parameterClass="String"&gt;
    delete from books where id = #id#
  &lt;/delete&gt;
  
&lt;/sqlMap&gt;
</pre>

<p>
The <code>Book.xml</code> file has three statements. It enables to 
select, insert and delete data. 
The values between the # characters are parameters to the sql map client. 
</p>


<div class="codehead">Book.java</div>
<pre class="code">
package com.zetcode;

import java.io.Serializable;

public class Book implements Serializable {

    private String id;
    private String author;
    private String title;
    private String year;
    private String remark;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }
}
</pre>

<p>
The <code>Book.java</code> file is the same as in the first example. 
</p>

<div class="codehead">DriverManagerExample.java</div>
<pre class="code">
function getBooks() {
  form = window.document.getElementById("form");
  form.action="GetAllBooks";
  form.submit();
}

function insertBook() {
  form = window.document.getElementById("form");
  form.action="InsertBook";
  form.submit();
}


function OnDelete() {

  var tbl = document.getElementById("books");
  var tds =  tbl.getElementsByTagName("td");

  var id;

  for(var i=0; i &lt; tds.length; ++i )
  {
      if (!(i%5))
          if (tds[i].parentNode.className == "selected") {
              id = tds[i].innerHTML;
          }
  }

  var form = document.getElementById("form");
  var input = document.getElementById("bookId");
  input.value=id;

  form.action="DeleteBooks";
  form.submit();
}

function select(obj) {
  if (obj.className != "selected") 
    obj.className = "hovered";

 }

function unselect(obj) {
  if (obj.className == "hovered")
    obj.className = "unselected";
}

function clicked(obj) {

  var tbl = document.getElementById("books");
  var trs = tbl.getElementsByTagName("tr");

  for(var l=0; l &lt; trs.length; ++l )
  {
    if (trs[l].className == "selected")
        trs[l].className = "unselected";
  }

  obj.className = "selected";
}
</pre>

<p>
This is the javascript that we use in our example. 
</p>


<pre class="explanation">
function getBooks() {
  form = window.document.getElementById("form");
  form.action="GetAllBooks";
  form.submit();
}
</pre>

<p>
The <code>getBooks()</code> function will call the 
<code>GetAllBooks</code> servlet.
</p>

<p>
The <code>insertBook()</code> function will call the 
<code>InsertBook</code> servlet.
The <code>OnDelete()</code> function will figure out, 
what row is currently selected and call the <code>DeleteBooks</code> servlet afterwards. 
</p>


<p>
If we hover a mouse pointer over a row in a table, we change it's colour to light blue. 
We do this using <code>select()</code> and <code>unselect()</code> 
JavaScript functions. 
</p>

<pre class="explanation">
function clicked(obj) {

  var tbl = document.getElementById("books");
  var trs = tbl.getElementsByTagName("tr");

  for(var l=0; l &lt; trs.length; ++l )
  {
    if (trs[l].className == "selected")
        trs[l].className = "unselected";
  }

  obj.className = "selected";
}
</pre>

<p>
If we click on a specific row, we change it's color to dark blue. 
The for loop makes sure, that  only one 
row is selected at a time. All previously selected rows get unselected. 
</p>


<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
   &lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
      &lt;title&gt;Books database&lt;/title&gt;
      &lt;link rel="stylesheet" href="style.css" type="text/css"&gt;
   &lt;/head&gt;

   &lt;script src="scripts.js"&gt;&lt;/script&gt;

 &lt;body&gt;
  &lt;br&gt;

  &lt;div class="navigator"&gt;
     &lt;a id="currenttab" href="index.jsp"&gt;Add&lt;/a&gt;
     &lt;a onclick="getBooks();"&gt;Show&lt;/a&gt;
  &lt;/div&gt;

  &lt;br&gt; &lt;br&gt; &lt;br&gt;


  &lt;form method="post" name="form" id="form"&gt;
   &lt;table&gt;
      &lt;tr&gt;    
          &lt;td&gt;Author&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="author"&gt;&lt;/td&gt;
      &lt;/tr&gt;    
      &lt;tr&gt;
          &lt;td&gt;Title&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="title"&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Year&lt;/td&gt;&lt;td&gt; &lt;input type="text" name="year"&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Remark&lt;/td&gt;&lt;td&gt; &lt;input type="text" name="remark"&gt;&lt;/td&gt;
      &lt;/tr&gt;

  &lt;/table&gt;

  &lt;input type="button" value="Insert" onclick="insertBook()"&gt;

  &lt;br&gt;    
  &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
This is the introdutory jsp file. It has a html form to add a new book to our database. 
</p>

<div class="codehead">show.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@page import="java.util.*" %&gt;
&lt;%@page import="com.zetcode.Book" %&gt;


&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;View&lt;/title&gt;
    &lt;link rel="stylesheet" href="style.css" type="text/css"&gt;
    &lt;script src="scripts.js"&gt;&lt;/script&gt;
  &lt;/head&gt;

 &lt;body&gt;

   &lt;br&gt;

    &lt;div class="navigator"&gt;
       &lt;a href="index.jsp"&gt;Add&lt;/a&gt;
       &lt;a id="currenttab" href="show.jsp"&gt;Show&lt;/a&gt;
    &lt;/div&gt;

    &lt;br&gt; &lt;br&gt; &lt;br&gt;
    &lt;form  method="get" id="form"&gt;
    &lt;input type="hidden" name="bookId" id="bookId"&gt;
    &lt;table id="books"&gt;
      &lt;tr&gt;
        &lt;th&gt;Id&lt;/th&gt;
        &lt;th&gt;Author&lt;/th&gt;
        &lt;th&gt;Title&lt;/th&gt;
        &lt;th&gt;Year&lt;/th&gt;
        &lt;th&gt;Remark&lt;/th&gt;
      &lt;/tr&gt; 
      &lt;%

      List&lt;com.zetcode.Book&gt; list = (List&lt;com.zetcode.Book&gt;) 
              session.getAttribute("books");

      for (Book a : list) {
          out.print("&lt;tr class='unselected' id='row' onclick='clicked(this)' " +
                  "onmouseout='unselect(this)' onmouseover='select(this)'&gt;");
          out.print("&lt;td id='id'&gt;");
          out.print(a.getId());
          out.print("&lt;/td&gt;");
          out.print("&lt;td&gt;");
          out.print(a.getAuthor());
          out.print("&lt;/td&gt;");
          out.print("&lt;td&gt;");
          out.print(a.getTitle());
          out.print("&lt;/td&gt;");
          out.print("&lt;td&gt;");
          out.print(a.getYear());
          out.print("&lt;/td&gt;");
          out.print("&lt;td&gt;");
          out.print(a.getRemark());
          out.print("&lt;/td&gt;");
          out.print("&lt;/tr&gt;");
      }
      %&gt;

      &lt;/table&gt;
      &lt;br&gt;
      &lt;input type="button" value="Delete" onclick="OnDelete()"&gt;

      &lt;/form&gt;

      &lt;br&gt;

  &lt;/body&gt;
&lt;/html>
</pre>

<p>
The <code>show.jsp</code> file shows the data from the books 
table. It also enables to delete a currently selected book from 
the database. 
</p>


<div class="codehead">DeleteBooks.java</div>
<pre class="code">
package com.zetcode;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.net.*;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;


public class DeleteBooks extends HttpServlet {


  protected void processRequest(HttpServletRequest request, 
          HttpServletResponse response)
  throws ServletException, IOException {

  response.setContentType("text/html;charset=UTF-8");


  try {
    Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
    SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

    String id = request.getParameter("bookId");
    sqlMap.delete("deleteBooks", id);


    } catch (SQLException ex) {
        Logger.getLogger(GetAllBooks.class.getName()
                ).log(Level.SEVERE, null, ex);

    } finally {

      RequestDispatcher dispatcher = 
                   request.getRequestDispatcher("/GetAllBooks");
      dispatcher.forward(request, response);
    }
 }


  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response)
  throws ServletException, IOException {
      processRequest(request, response);
  } 


  protected void doPost(HttpServletRequest request, 
      HttpServletResponse response)
  throws ServletException, IOException {
      processRequest(request, response);
  }
}
</pre>

<p>
The <code>DeleteBooks</code> servlet deletes a book from the database. 
</p>

<pre class="explanation">
String id = request.getParameter("bookId");
sqlMap.delete("deleteBooks", id);
</pre>

<p>
We get the id of the book from the request. The id is given to the 
sql map client delete statement. 
</p>

<pre class="explanation">
RequestDispatcher dispatcher = request.getRequestDispatcher("/GetAllBooks");
dispatcher.forward(request, response);
</pre>

<p>
After we delete the book, we call the <code>GetAllBooks</code> servlet. 
</p>

<div class="codehead">GetAllBooks.java</div>
<pre class="code">
package com.zetcode;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.sql.*;
import java.io.*;
import java.net.*;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetAllBooks extends HttpServlet {


  protected void processRequest(HttpServletRequest request,
          HttpServletResponse response)
       throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");

    try {

      Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
      SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

      List&lt;Book&gt; books = (List&lt;Book&gt;) sqlMap.queryForList("selectAllBooks");
      request.getSession().setAttribute("books", books);

      } catch (SQLException ex) {
          Logger.getLogger(GetAllBooks.class.getName()).log(
                  Level.SEVERE, null, ex);

      } finally {
          RequestDispatcher dispatcher = 
                         request.getRequestDispatcher("/show.jsp");
          dispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, 
        HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, 
        HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}
</pre>

<p>
The <code>GetAllBooks</code> servlet selects all data from the books table and
put it into the session object. Later in the show.jsp file we retrieve this data. 
</p>

<pre class="explanation">
List&lt;Book&gt; books = (List&lt;Book&gt;) sqlMap.queryForList("selectAllBooks");
request.getSession().setAttribute("books", books);
</pre>

<p>
Here we select the data and put it into the session. 
</p>

<div class="codehead">InsertBook.java</div>
<pre class="code">
package com.zetcode;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.sql.*;
import java.io.*;
import java.net.*;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

public class InsertBook extends HttpServlet {



  protected void processRequest(HttpServletRequest request,
          HttpServletResponse response)
          throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");

  String author = request.getParameter("author");
  String title = request.getParameter("title");
  String year = request.getParameter("year");
  String remark = request.getParameter("remark");

  try {

    Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
    SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);


    Book book = new Book();

    book.setAuthor(author);
    book.setTitle(title);
    book.setYear(year);
    book.setRemark(remark);

    sqlMap.insert("insertBook", book);


  } catch (SQLException ex) {
    Logger.getLogger(GetAllBooks.class.getName()).log(
                       Level.SEVERE, null, ex);

  } finally {

    RequestDispatcher dispatcher = 
                       request.getRequestDispatcher("/GetAllBooks");
    dispatcher.forward(request, response);
    }
  }

  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response)
          throws ServletException, IOException {
      processRequest(request, response);
  }

  protected void doPost(HttpServletRequest request, 
      HttpServletResponse response)
          throws ServletException, IOException {
      processRequest(request, response);
  }
}

</pre>

<p>
The <code>InsertBook</code> servlet inserts a new book into the database. 
</p>

<pre class="explanation">
String author = request.getParameter("author");
String title = request.getParameter("title");
String year = request.getParameter("year");
String remark = request.getParameter("remark");
</pre>

<p>
We get the necessary data from the request. 
</p>

<pre class="explanation">
Book book = new Book();

book.setAuthor(author);
book.setTitle(title);
book.setYear(year);
book.setRemark(remark);
</pre>

<p>
Create and fill the Book class. 
</p>

<pre class="explanation">
sqlMap.insert("insertBook", book);
</pre>

<p>
Insert the data into the database using the sql map client. 
</p>

<img src="/img/java/jee/ibatis.png" alt="iBATIS">
<div class="figure">Figure: iBATIS</div>

<p>
In this chapter we have shortly talked about ORM with iBATIS.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified April 14, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

